package com.qubaopen.core.utils;



import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.util.Formatter;

/**
 * 采用MD5或SHA1方式，生成文件的CheckSum值
 * 
 * @author Zhangyongyi
 * 
 */

public class CheckSumUtil {

	/**
	 * 将byte数组转换为十六进制的字符串
	 * 
	 * @param hash
	 * @return
	 */
	public static String byteArray2Hex(byte[] hash) {
		Formatter formatter = new Formatter();
		for (byte b : hash) {
			formatter.format("%02x", b);
		}

		return formatter.toString();
	}

	/**
	 * 根据加密算法，获取指定文件的CheckSum值
	 * 
	 * @param algorithm
	 *            例如：MessageDigest.getInstance("SHA1")或MessageDigest.getInstance
	 *            ("MD5")
	 * @param fileName
	 * @return
	 * @throws Exception
	 */
	public static String calculateChecksum(MessageDigest algorithm,
			String fileName) {

		byte[] buffer = new byte[2048];
		FileInputStream fis = null;
		BufferedInputStream bis = null;
		DigestInputStream dis = null;

		try {
			fis = new FileInputStream(fileName);
			bis = new BufferedInputStream(fis);
			dis = new DigestInputStream(bis, algorithm);

			// read the file and update the hash calculation
			while (dis.read(buffer, 0, 2048) != -1)
				;

			// get the hash value as byte array
			byte[] hash = algorithm.digest();

			return byteArray2Hex(hash);
			
		} catch (Exception e) {
			return "";

		} finally {

			try {
				if (dis != null) {
					dis.close();
				}

				if (bis != null) {
					bis.close();
				}

				if (fis != null) {
					fis.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
